package fr.inria.phoenix.scenario.bwsnfirefighting.impl.controller;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import fr.inria.diagen.core.ServiceConfiguration;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.DangerLevel;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.DeviceStatus;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.datatype.Location;
import fr.inria.phoenix.scenario.bwsnfirefighting.framework.distributed.logmanager.LogManager;

public class LogManagerImpl extends LogManager {

	private String logfile = "alarm.log";
	private FileWriter log;
	
	public LogManagerImpl(ServiceConfiguration serviceConfiguration) throws IOException {
		super(serviceConfiguration);
		log = new FileWriter(logfile);
	}

	@Override
	public void onNewAlertDetection(DangerLevel newAlertDetectionValue,
			Location location) {
		BufferedWriter out = new BufferedWriter(log);
		SimpleDateFormat formatter=  new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
		String logItem = formatter.format(Calendar.getInstance());
		if (newAlertDetectionValue == DangerLevel.SAFE){
			logItem += " -> Detected SAFE state";
		}
		else if (newAlertDetectionValue == DangerLevel.WARNING){
			logItem += " -> Detected WARNING state";
		}
		else if (newAlertDetectionValue == DangerLevel.ALERT){
			logItem += " -> Detected ALERT state";
		}
		logItem += " in FLOOR: " + location.getFloor() + ", ROOM: " + location.getRoom();
		logItem += "\n";
		try {
			out.write(logItem);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void onNewStatusDetection(DeviceStatus newStatusDetectionValue,
			Integer id) {
		BufferedWriter out = new BufferedWriter(log);
		SimpleDateFormat formatter=  new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
		String logItem = formatter.format(Calendar.getInstance());
		if (newStatusDetectionValue == DeviceStatus.FAULT){
			logItem += " -> Detected Fault state of the device " + id;
		}
		else {
			logItem += " -> Detected WORKING state of the device " + id;
		}
		logItem += "\n";
		try {
			out.write(logItem);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}
